package com.demo.factory;

import com.demo.GreetAboutTime;
import com.demo.GreetToUser;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigFactory {
    private static GreetAboutTime greetAboutTime;
    private static GreetToUser greetToUser;
    private static final String PROP_FILE = "app.properties";

    public ConfigFactory() {
        Properties props = readPropertiesFile();
        loadGreetAboutTime(props);
        loadGreetToUser(props);
    }

    private Properties readPropertiesFile() {
        try {
            Properties props = new Properties();
            InputStream is = this.getClass().getClassLoader().getResourceAsStream(PROP_FILE);
            if(is==null) throw new RuntimeException("Not found property file: "+PROP_FILE);
            props.load(is);
            return props;
        } catch (IOException e) {
            throw new RuntimeException("read property file error!",e);
        }
    }

    private void loadGreetAboutTime(Properties props) {
        String className = props.getProperty("greetAboutTime");
        if(className==null||"".equals(className)) return;
        try {
            greetAboutTime = (GreetAboutTime) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("The class not found: "+className);
        } catch (InstantiationException e) {
            throw new RuntimeException("error when instantiate the class: "+className);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Illegal access the class: "+className);
        }
    }

    private void loadGreetToUser(Properties props) {
        String className = props.getProperty("greetToUser");
        if(className==null||"".equals(className)) return;
        try {
            greetToUser = (GreetToUser) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("The class not found: "+className);
        } catch (InstantiationException e) {
            throw new RuntimeException("error when instantiate the class: "+className);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Illegal access the class: "+className);
        }
    }

    public static GreetAboutTime getGreetAboutTime() {
        return greetAboutTime;
    }

    public static GreetToUser getGreetToUser() {
        return greetToUser;
    }
}
